package br.usp.ime.dojo.server;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import br.usp.ime.dojo.client.DojoException;
import br.usp.ime.dojo.client.JRubyInterpreterService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class JRubyInterpreterServiceImpl extends RemoteServiceServlet implements JRubyInterpreterService {

	private static final long serialVersionUID = 1L;

	public String interpret(String code, String testCode) throws DojoException {
		try {
			ScriptEngineManager engineManager = new ScriptEngineManager();
			
			ScriptEngine jruby = null;
			
			jruby = engineManager.getEngineByName("jruby");
			if(code == null)
				System.err.println(">>>>>code is null!");
			if(jruby == null)
				System.err.println(">>>>>interpreter is null!");
			
			jruby.eval(code);
			jruby.eval("$rubymsg = \"\"\ndef show msg\n$rubymsg = $rubymsg + msg + \"\n\"\nend");
			jruby.eval(testCode);
			String resp = (String) jruby.getBindings(ScriptContext.ENGINE_SCOPE).get("rubymsg");			
			return resp;
		}
		catch(ScriptException ex) {
			throw new DojoException(ex.getMessage());
		}
	}

}
